package cn.study.project.textswitcher;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.ViewSwitcher;

import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity implements ViewSwitcher.ViewFactory {

    private TextSwitcher mTextSwitcher;
    private int myID=0;
    String[] myItems={"神奇宝贝1","神奇宝贝2","神奇宝贝3","神奇宝贝4","神奇宝贝5","神奇宝贝6","神奇宝贝7"
            ,"神奇宝贝8","神奇宝贝9","神奇宝贝10"};
    private Timer mTimer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextSwitcher=findViewById(R.id.text_switcher);
        mTextSwitcher.setFactory(this);

        Animation mSwitchIn= AnimationUtils.loadAnimation(this,android.R.anim.slide_in_left);
        Animation mSwitchOut= AnimationUtils.loadAnimation(this,android.R.anim.slide_out_right);

        mTextSwitcher.setInAnimation(mSwitchIn);
        mTextSwitcher.setOutAnimation(mSwitchOut);
        updateCounter();

        findViewById(R.id.start).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myID=0;
                if(mTimer!=null) mTimer.cancel();
                mTimer=new Timer();
                mTimer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                    updateCounter();
                                }
                        });
                    }},0,2000);

            }
        });

        findViewById(R.id.stop).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTimer.cancel();
            }
        });
    }



    private void updateCounter(){
        mTextSwitcher.setText(myItems[myID]);
        myID++;
        myID=myID%10;
    }

    @Override
    public View makeView() {
        TextView mTextView=new TextView(this);
        mTextView.setGravity(Gravity.TOP|Gravity.CENTER_HORIZONTAL);
        mTextView.setTextSize(36);
        mTextView.setTextColor(Color.YELLOW);
        return mTextView;
    }
}